package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.core.util.ResultStatusEnum;
import cn.stylefeng.guns.modular.system.dto.*;
import cn.stylefeng.guns.modular.system.model.GameConfig;
import cn.stylefeng.guns.modular.system.model.GameUser;
import cn.stylefeng.guns.modular.system.model.Order;
import cn.stylefeng.guns.modular.system.service.IGameConfigService;
import cn.stylefeng.guns.modular.system.service.IGameUserService;
import cn.stylefeng.guns.modular.system.service.IOrderService;
import cn.stylefeng.guns.modular.system.service.IScoreLevelService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.nineshadow.games.Enum.GameTypeEnum;
import com.nineshadow.games.launch.HallServer;
import com.nineshadow.games.util.UploadFileUtils;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RestController
@RequestMapping("/bixinApi/")
public class BixingInterfaceController {

    public static final String DOMAIN="api.hibixin.com/open";
//    public static final String TEST_API_DOMAIN="http://test-api.hibixin.com/open";
    public static final String TEST_API_DOMAIN="https://api.hibixin.com/open";
    public static final String SUCCESS_CODE="30000";

    public static String refreshToken="";

    @Autowired
    private IGameUserService gameUserService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IGameConfigService gameConfigService;

    @Autowired
    private IScoreLevelService scoreLevelService;

    @Autowired
    private UploadFileUtils uploadFileUtils;

    public static AtomicInteger number = new AtomicInteger(0);

    /**
     * 兑换token
     * @param code
     * @return
     */
    @RequestMapping("oauth/token")
    public Map<String,Object> token(String code,int gameType){
        log.info("兑换token:{}",code);
        if (StringUtils.isBlank(code)){
            return ResultStatusEnum.putFailureMsg(new HashMap<>(),"code不能为空");
        }
        try{
            GetTokenDto token = getToken(code, GameTypeEnum.getByType(gameType),false);
            if (token != null){
                GameUser gameUser = gameUserService.selectOne(new EntityWrapper<GameUser>().eq("open_id", token.getOpenId()));
                if (gameUser == null){
                    gameUser = new GameUser();
                    gameUser.setOpenId(token.getOpenId());
                    gameUser.setCreateTime(new Date());
                    gameUserService.insert(gameUser);
                }
                Map<String,Object> resultMap = new HashMap<>();
                resultMap.put("openId",token.getOpenId());
                resultMap.put("id",gameUser.getId());
                log.info("兑换token结果:{}",resultMap);
                return ResultStatusEnum.putSuccessMsg(resultMap,"操作成功");
            }
        }catch (Exception e){
            log.error("code不合法:{}",e);
        }
        return ResultStatusEnum.putFailureMsg(new HashMap<>(),"获取失败");
    }

//    /**
//     * 创建订单
//     * @param openId
//     * @param productName
//     * @param totalAmount
//     */
//    @RequestMapping("/order/create")
//    public Map<String,Object> createOrder(String openId,String productName,double totalAmount){
//        if (StringUtils.isBlank(productName)){
//            productName = "-";
//        }
//        Order localOrder = createLocalOrder(openId, productName, totalAmount);
//        String resoucesAuthorization = getResourcesAuthorization();
//        if (StringUtils.isBlank(resoucesAuthorization)){
//            return ResultStatusEnum.putFailureMsg(new HashMap<>(),"授权失败");
//        }
//        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
//        headers.add("Authorization",resoucesAuthorization);
//        CreateOrderRequestDto createOrderRequestDto = new CreateOrderRequestDto();
//        createOrderRequestDto.setReferenceOrderId(localOrder.getReferenceOrderId());
//        createOrderRequestDto.setOpenId(openId);
//        createOrderRequestDto.setProductName(productName);
//        createOrderRequestDto.setTotalAmount(totalAmount);
//        ResourceUnionRequestDto<CreateOrderRequestDto> resourceUnionRequestDto = new ResourceUnionRequestDto<>(gameType,createOrderRequestDto);
//        HttpEntity entity = new HttpEntity(resourceUnionRequestDto,headers);
//        ResponseEntity<ResourceUnionResponseDto<Map<String,Object>>> exchange = HallServer.restTemplate.exchange(TEST_API_DOMAIN + "/order/create", HttpMethod.POST, entity, (Class<ResourceUnionResponseDto<Map<String,Object>>>) new ResourceUnionResponseDto<Map<String,Object>>().getClass());
//        log.info("创建订单结果：{}",exchange);
//        if (exchange.getStatusCode().equals(HttpStatus.OK) && SUCCESS_CODE.equals(exchange.getBody().getRet())){
//            Map<String,Object> result = exchange.getBody().getResult();
//            localOrder.setPayId(String.valueOf(result.get("payId")));
//            orderService.updateById(localOrder);
//            Map<String,Object> maps = new HashMap<>();
//            maps.put("referenceOrderId",localOrder.getReferenceOrderId());
//            maps.put("payId",localOrder.getPayId());
//            return ResultStatusEnum.putSuccessMsg(maps,"操作成功!");
//        }
//        return ResultStatusEnum.putFailureMsg(new HashMap<>(),"操作失败");
//    }

//    private Order createLocalOrder(String openId, String productName, double totalAmount) {
//        Order order = new Order();
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        String format = simpleDateFormat.format(new Date());
//        String  numberStr= StringUtils.leftPad(String.valueOf(number.getAndIncrement()),3,"0");
//        order.setOpenId(openId);
//        order.setReferenceOrderId(format+"_"+numberStr);
//        order.setAppId(appId);
//        order.setProductName(productName);
//        order.setTotalAmount(BigDecimal.valueOf(totalAmount));
//        order.setState("CREATE");
//        order.setCreateTime(new Date());
//        orderService.insert(order);
//        return order;
//    }

//    @RequestMapping("/payRedirect")
//    public String payRedirectUrl(PayRedirectDto payRedirectDto){
//        log.info("支付回调:{}",payRedirectDto);
//        Wrapper<Order> wrapper = new EntityWrapper<Order>().eq("pay_id",payRedirectDto.getPayId()).eq("app_id",appId);
//        Order order = orderService.selectOne(wrapper);
//        order.setAttach(payRedirectDto.getAttach());
//        order.setAttachNo(payRedirectDto.getAttachNo());
//        order.setOrderNo(payRedirectDto.getOrderNo());
////        order.setAppId(payRedirectDto.getAppId());
//        order.setMerchantId(payRedirectDto.getMerchantId());
////        order.setState(payRedirectDto.getState());
//        order.setPayTime(payRedirectDto.getPayTime());
//        order.setPayChannel(payRedirectDto.getPayChannel().toString());
//        order.setPayPlatform(payRedirectDto.getPayPlatform().toString());
//        order.setPayNoThird(payRedirectDto.getPayNoThird());
//        orderService.updateById(order);
//        return "success";
//    }

    /**
     * 支付信息查询
     * @param payInfoQueryQuest
     */
//    @RequestMapping("/pay/query")
//    public Map<String,Object> queryInfo(PayInfoQueryQuest payInfoQueryQuest){
//        ResourceUnionRequestDto<PayInfoQueryQuest> requestDto = new ResourceUnionRequestDto<>(appId,appSecret,payInfoQueryQuest);
//        String resoucesAuthorization = getResourcesAuthorization();
//        if (StringUtils.isBlank(resoucesAuthorization)){
//            return ResultStatusEnum.putFailureMsg(new HashMap<>(),"获取授权失败");
//        }
//        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
//        headers.add("Authorization",resoucesAuthorization);
//        HttpEntity entity = new HttpEntity(requestDto,headers);
//        ResponseEntity<ResourceUnionResponseDto> exchange = HallServer.restTemplate.exchange(TEST_API_DOMAIN + "/pay/query", HttpMethod.POST, entity,ResourceUnionResponseDto.class);
//        log.info("查询支付信息:{}",exchange);
//        if (exchange.getStatusCode().equals(HttpStatus.OK) && SUCCESS_CODE.equals(exchange.getBody().getRet())){
//            PayInfoResponse payInfoResponse = JSONObject.parseObject(JSONObject.toJSONString(exchange.getBody().getResult()),PayInfoResponse.class);
//            Wrapper<Order> wrapper = new EntityWrapper<Order>().eq("order_no", payInfoQueryQuest.getOrderNo()).eq("pay_id", payInfoQueryQuest.getAppId())
//                    .eq("app_id", payInfoQueryQuest.getPayId()).eq("merchant_id", payInfoQueryQuest.getMerchantId());
////            Order order = orderService.selectOne(wrapper);
//            Map<String,Object> result = new HashMap<>();
//            result.put("data",payInfoResponse);
//            return ResultStatusEnum.putSuccessMsg(result,"获取成功");
//        }
//        return ResultStatusEnum.putFailureMsg(new HashMap<>(),"获取失败");
//    }

    /**
     * 获取用户头像
     * @param openId
     */
    @RequestMapping("v1/user/info")
    public Map<String,Object> getUserAvatar(String openId,int gameType){
        log.info("获取用户头像:{}",openId);
        try {
            if (StringUtils.isBlank(openId)){
                return ResultStatusEnum.putFailureMsg(new HashMap<>(),"openId不能为空");
            }
            String resoucesAuthorization = getResourcesAuthorization(GameTypeEnum.getByType(gameType));
            if (StringUtils.isBlank(resoucesAuthorization)){
                return ResultStatusEnum.putFailureMsg(new HashMap<>(),"授权失败");
            }
            MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
            headers.add("Authorization",resoucesAuthorization);
            headers.add("Content-Type","application/json;charset=UTF-8");
            Map<String,String> parameterMap = new HashMap<>();
            parameterMap.put("openId",openId);
            ResourceUnionRequestDto<Map<String,String>> requestDto = new ResourceUnionRequestDto<Map<String,String>>(GameTypeEnum.getByType(gameType),parameterMap);
            String s = JSONObject.toJSONString(requestDto);
            HttpEntity entity = new HttpEntity(s,headers);
            ResponseEntity<ResourceUnionResponseDto> exchange = HallServer.restTemplate.exchange(TEST_API_DOMAIN + "/v1/user/info", HttpMethod.POST, entity, ResourceUnionResponseDto.class);
            log.info("获取用户信息:{}",exchange);
            if (exchange.getStatusCode().equals(HttpStatus.OK) && SUCCESS_CODE.equals(exchange.getBody().getRet())){
                UserInfoDto userInfoDto = JSONObject.parseObject(JSONObject.toJSONString(exchange.getBody().getResult()),UserInfoDto.class);
                GameUser gameUser = gameUserService.selectOne(new EntityWrapper<GameUser>().eq("open_id", openId));
                gameUser.setNickName(userInfoDto.getNickName());
                gameUser.setGender(userInfoDto.getGender());
                gameUser.setAvatar(userInfoDto.getAvatar());
                gameUserService.updateById(gameUser);
                Map<String,Object> map=scoreLevelService.getUserLevel(gameUser.getId(),gameType);
                userInfoDto.setLevel(map.get("level").toString());
                userInfoDto.setRatio((double)map.get("ratio"));
                Map<String,Object> msg = new HashMap<>();
                msg.put("info", userInfoDto);
                return ResultStatusEnum.putSuccessMsg(msg,"操作成功");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return ResultStatusEnum.putFailureMsg(new HashMap<>(),"操作失败");
    }

    /**
     * 好友关注
     * @param fromOpenId
     * @param toOpenId
     */
    @RequestMapping("/v1/user/follow")
    public Map<String,Object> follow(String fromOpenId,String toOpenId,int gameType,String ua){
        log.info("好友关注:{}->{}",fromOpenId,toOpenId);
        log.info("新增参数ua:{}",ua);
        if (StringUtils.isBlank(fromOpenId) || StringUtils.isBlank(toOpenId)){
            return ResultStatusEnum.putFailureMsg(new HashMap<>(),"openIds不能为空");
        }
        try {
            boolean b = watchFriend(fromOpenId, toOpenId, false,GameTypeEnum.getByType(gameType));
            return b?ResultStatusEnum.putSuccessMsg(new HashMap<>(),"成功"):ResultStatusEnum.putFailureMsg(new HashMap<>(),"失败");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return ResultStatusEnum.putFailureMsg(new HashMap<>(),e.getMessage());
        }
    }

    /**
     * 关注关系
     * @param fromOpenId
     * @param toOpenId
     */
    @RequestMapping("/v1/user/relation")
    public boolean relation(String fromOpenId,String toOpenId,int gameType){
        log.info("关注关系:{}={}",fromOpenId,toOpenId);
        if (StringUtils.isBlank(fromOpenId) || StringUtils.isBlank(toOpenId)){
            throw new RuntimeException("fromOpenId与toOpenId不能为空");
        }
        try {
            return watchFriend(fromOpenId, toOpenId, true,GameTypeEnum.getByType(gameType));
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return false;
        }
    }

    /**
     * 创建房间
     * @param openIds
     */
    @RequestMapping("/v1/voiceRoom/create")
    public Map<String,Object> createVoiceRoom(String openIds,int gameType){
        log.info("开始创建房间:{}",openIds);
        Map<String,Object> maps = new HashMap<>();
        try {
            Long voiceRoomId=voiceRoom(openIds,GameTypeEnum.getByType(gameType));
            maps.put("roomId",String.valueOf(voiceRoomId));
            return ResultStatusEnum.putSuccessMsg(maps,"创建成功!");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return ResultStatusEnum.putFailureMsg(new HashMap<>(),"创建失败");
        }
    }

    public static Long voiceRoom(String openIds,GameTypeEnum gameTypeEnum) throws Exception{
        log.info("openIds：{}--roomType:{}",openIds,gameTypeEnum.getMsg());
        if (StringUtils.isBlank(openIds)){
            throw new RuntimeException("openIds不能为空");
        }
        String resoucesAuthorization = getResourcesAuthorization(gameTypeEnum);
        if (StringUtils.isBlank(resoucesAuthorization)){
            throw new RuntimeException("授权失败");
        }
        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization",resoucesAuthorization);
        Map<String,String> parameterMap = new HashMap<>();
        parameterMap.put("openIds",openIds);
        ResourceUnionRequestDto<Map<String,String>> requestDto = new ResourceUnionRequestDto<Map<String,String>>(gameTypeEnum,parameterMap);
        HttpEntity entity = new HttpEntity(requestDto,headers);
        ResponseEntity<ResourceUnionResponseDto<Long>> exchange = HallServer.restTemplate.exchange(TEST_API_DOMAIN + "/v1/voiceRoom/create", HttpMethod.POST, entity, (Class<ResourceUnionResponseDto<Long>>) new ResourceUnionResponseDto<Long>().getClass());
        log.info("创建房间:{}",exchange);
        if (!exchange.getStatusCode().equals(HttpStatus.OK) || !SUCCESS_CODE.equals(exchange.getBody().getRet())){
            throw new RuntimeException("创建语音房间失败");
        }
        Long result = exchange.getBody().getResult();
        return result;
    }

    /**
     * 解散房间
     * @param roomId
     */
    @RequestMapping("/v1/voiceRoom/remove")
    public boolean removeRoom(String roomId,int gameType){
        try {
            removeVoiceRoom(roomId,GameTypeEnum.getByType(gameType));
            return true;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return false;
    }


    public static void removeVoiceRoom(String roomId,GameTypeEnum gameTypeEnum) throws Exception {
        log.info("开始解散房间:{}", roomId);
        if (StringUtils.isBlank(roomId)) {
            throw new RuntimeException("房间Id不能为空");
        }
        String resoucesAuthorization = getResourcesAuthorization(gameTypeEnum);
        if (StringUtils.isBlank(resoucesAuthorization)) {
            throw new RuntimeException("授权失败");
        }
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization", resoucesAuthorization);
        Map<String, Long> parameterMap = new HashMap<>();
        parameterMap.put("roomId", Long.valueOf(roomId));
        ResourceUnionRequestDto<Map<String, Long>> requestDto = new ResourceUnionRequestDto<Map<String, Long>>(gameTypeEnum, parameterMap);
        HttpEntity entity = new HttpEntity(requestDto, headers);
        ResponseEntity<ResourceUnionResponseDto> exchange = HallServer.restTemplate.exchange(TEST_API_DOMAIN + "/v1/voiceRoom/remove", HttpMethod.POST, entity, ResourceUnionResponseDto.class);
        log.info("解散房间:{}", exchange);
        if (!exchange.getStatusCode().equals(HttpStatus.OK) || !SUCCESS_CODE.equals(exchange.getBody().getRet())) {
            throw new RuntimeException("解散语音房间失败");
        }
    }

    /**
     * 离开房间
     * @param roomId
     * @param openId
     */
//    @RequestMapping("/v1/voiceRoom/leave")
    public Map<String,Object> leaveRoom(String roomId,String openId,int gameType){
        try {
            quitRoom(roomId,openId,GameTypeEnum.getByType(gameType));
            return ResultStatusEnum.putSuccessMsg(new HashMap<>(),"操作成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return ResultStatusEnum.putFailureMsg(new HashMap<>(),"操作失败");
    }

    public static void quitRoom(String roomId,String openId,GameTypeEnum gameTypeEnum)throws Exception{
        if (StringUtils.isBlank(roomId) || StringUtils.isBlank(openId)){
            throw new RuntimeException("房间id或openId不能为空");
        }
        String resoucesAuthorization = getResourcesAuthorization(gameTypeEnum);
        if (StringUtils.isBlank(resoucesAuthorization)){
            throw new RuntimeException("授权失败");
        }
        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization",resoucesAuthorization);
        Map<String,Object> parameterMap = new HashMap<>();
        parameterMap.put("roomId",Long.valueOf(roomId));
        parameterMap.put("openId",openId);
        ResourceUnionRequestDto<Map<String,Object>> requestDto = new ResourceUnionRequestDto<Map<String,Object>>(gameTypeEnum,parameterMap);
        HttpEntity entity = new HttpEntity(requestDto,headers);
        ResponseEntity<ResourceUnionResponseDto<Boolean>> exchange = HallServer.restTemplate.exchange(TEST_API_DOMAIN + "/v1/voiceRoom/leave", HttpMethod.POST, entity, (Class<ResourceUnionResponseDto<Boolean>>) new ResourceUnionResponseDto<Boolean>().getClass());
        log.info("离开房间:{}",exchange);
        if (!exchange.getStatusCode().equals(HttpStatus.OK) || !SUCCESS_CODE.equals(exchange.getBody().getRet())){
           throw new RuntimeException("离开语音房间失败");
        }
        boolean result = exchange.getBody().getResult();
        if(result){
            throw new RuntimeException("离开语音房间失败");
        }
    }

    /**
     * 加入房间
     * @param roomId
     * @param openIds
     */
//    @RequestMapping("/v1/voiceRoom/join")
    public Map<String,Object> joinRoom(String roomId,String openIds,int gameType){
        try {
            openVoice(roomId,openIds,GameTypeEnum.getByType(gameType));
            return ResultStatusEnum.putSuccessMsg(new HashMap<>(),"操作成功");
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return ResultStatusEnum.putFailureMsg(new HashMap<>(),"操作失败");
    }

    public static void openVoice(String roomId,String openIds,GameTypeEnum gameTypeEnum){
        if (StringUtils.isBlank(roomId) || StringUtils.isBlank(openIds)){
            log.error("房间id或openids不能为空");
            throw new RuntimeException("房间id或openids不能为空");
        }
        String resoucesAuthorization = getResourcesAuthorization(gameTypeEnum);
        if (StringUtils.isBlank(resoucesAuthorization)){
            throw new RuntimeException("授权失败");
        }
        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization",resoucesAuthorization);
        Map<String,Object> parameterMap = new HashMap<>();
        parameterMap.put("roomId",Long.valueOf(roomId));
        parameterMap.put("openIds",openIds);
        ResourceUnionRequestDto<Map<String,Object>> requestDto = new ResourceUnionRequestDto<Map<String,Object>>(gameTypeEnum,parameterMap);
        HttpEntity entity = new HttpEntity(requestDto,headers);
        ResponseEntity<ResourceUnionResponseDto<Boolean>> exchange = HallServer.restTemplate.exchange(TEST_API_DOMAIN + "/v1/voiceRoom/join", HttpMethod.POST, entity, (Class<ResourceUnionResponseDto<Boolean>>) new ResourceUnionResponseDto<Boolean>().getClass());
        log.info("加入房间:{}",exchange);
        if (!exchange.getStatusCode().equals(HttpStatus.OK) || !SUCCESS_CODE.equals(exchange.getBody().getRet())){
            throw new RuntimeException("加入语音房间失败");
        }
        boolean result = exchange.getBody().getResult();
        if(result){
            throw new RuntimeException("加入语音房间失败");
        }
    }


    public static boolean watchFriend(String fromOpenId,String toOpenId,boolean isGetWatchResult,GameTypeEnum gameTypeEnum)throws Exception{
        log.info("关注接口：:  fromOpenId:{}--toOpenId:{}--isGetWatchResult:{}--gameTypeEnum:{}",fromOpenId,toOpenId,isGetWatchResult,gameTypeEnum.getMsg());
        String resoucesAuthorization = getResourcesAuthorization(gameTypeEnum);
        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization",resoucesAuthorization);
        Map<String,String> parameterMap = new HashMap<>();
        parameterMap.put("fromOpenId",fromOpenId);
        parameterMap.put("toOpenId",toOpenId);
        ResourceUnionRequestDto<Map<String,String>> requestDto = new ResourceUnionRequestDto<Map<String,String>>(gameTypeEnum,parameterMap);
        HttpEntity entity = new HttpEntity(requestDto,headers);
        String url = isGetWatchResult?TEST_API_DOMAIN+"/v1/user/relation":TEST_API_DOMAIN + "/v1/user/follow";
        ResponseEntity<ResourceUnionResponseDto<Boolean>> exchange = HallServer.restTemplate.exchange(url, HttpMethod.POST, entity, (Class<ResourceUnionResponseDto<Boolean>>) new ResourceUnionResponseDto<Boolean>().getClass());
        log.info("好友关注结果:{}",exchange);
        if (exchange.getStatusCode().equals(HttpStatus.OK) && SUCCESS_CODE.equals(exchange.getBody().getRet())){
            Boolean result = exchange.getBody().getResult();
            return result;
        }
        return false;
    }

    public GetTokenDto getToken(String code,GameTypeEnum gameTypeEnum,boolean isRefresh){
        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
        String authorization = getAuthorization(gameTypeEnum);
        headers.add("Authorization",authorization);
        HttpEntity httpEntity = new HttpEntity(headers);
        String url = generateGetTokenUrl(code,isRefresh);
        ResponseEntity<GetTokenDto> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, GetTokenDto.class);
        log.info("返回结果:{}",exchange);
        if (exchange.getStatusCode().equals(HttpStatus.OK)){
            refreshToken = exchange.getBody().getRefresh_token();
            return exchange.getBody();
        }
        return null;
    }

    private static String getAuthorization(GameTypeEnum gameTypeEnum){
        String authorization = "Basic "+ Base64Utils.encodeToString((gameTypeEnum.getAppId()+":"+gameTypeEnum.getAppSecret()).getBytes(StandardCharsets.UTF_8));
        return authorization;
    }

    public static GetAuthDto getOauthToken(GameTypeEnum gameTypeEnum){
        String authorization = getAuthorization(gameTypeEnum);
        MultiValueMap headers = new LinkedMultiValueMap();
        headers.add("Authorization",authorization);
        String url = generateGetOauthTokenUrl();
        HttpEntity entity = new HttpEntity(headers);
        ResponseEntity<GetAuthDto> exchange = HallServer.restTemplate.exchange(url, HttpMethod.POST, entity, GetAuthDto.class);
        log.info("返回结果:{}",exchange);
        if (exchange.getStatusCode().equals(HttpStatus.OK)){
            return exchange.getBody();
        }
       return null;
    }

    public static String getResourcesAuthorization(GameTypeEnum gameTypeEnum){
        String authorization = null;
        //access_token没有过期，取数据库中，过期重新请求access_token
        GameConfig gameConfig = HallServer.gameConfigService.selectOne(new EntityWrapper<GameConfig>().eq("type", gameTypeEnum.getType()+"_access_token"));
        if (StringUtils.isNotBlank(gameConfig.getName())){
            String value = gameConfig.getValue();
            Long endTime = Long.valueOf(value);
//            距离失效时间大于2秒
            if (System.currentTimeMillis() - endTime < 2000){
                authorization = "Bearer "+ gameConfig.getName();
            }
        }
        if (authorization == null){
            GetAuthDto oauthToken = getOauthToken(gameTypeEnum);
            if (oauthToken != null){
                authorization = "Bearer "+ oauthToken.getAccess_token();
                gameConfig.setName(oauthToken.getAccess_token());
                int expiresIn = oauthToken.getExpires_in();
                long endTime = System.currentTimeMillis() + expiresIn * 1000;
                gameConfig.setValue(String.valueOf(endTime));
                HallServer.gameConfigService.updateById(gameConfig);
            }
        }
        return authorization;
    }

    private static String generateGetTokenUrl(String code,boolean isRefresh) {
        String url = "";
        if (!isRefresh){
            url = TEST_API_DOMAIN+"/oauth/token?response_type=token&code={code}&grant_type=authorization_code";
        }else {
            url=TEST_API_DOMAIN+"/oauth/token?response_type=token&refresh_token={code}&grant_type=refresh_token";
            if (StringUtils.isBlank(refreshToken)){
                log.error("还没有获取过token");
                throw new RuntimeException("还没有获取过token");
            }
        }
        return url.replace("{code}",code);
    }
    private static String generateGetOauthTokenUrl() {
        return TEST_API_DOMAIN+"/oauth/token?grant_type=client_credentials";
    }
}
